using MediatR;
using TerritoryGame.Application.Queries;
using TerritoryGame.Domain.Entities;
using TerritoryGame.Domain.Repositories;

namespace TerritoryGame.Application.Handlers.QueryHandlers;

public class GetRoomQueryHandler : IRequestHandler<GetRoomQuery, GetRoomResult>
{
    private readonly IGameRoomRepository _gameRoomRepository;

    public GetRoomQueryHandler(IGameRoomRepository gameRoomRepository)
    {
        _gameRoomRepository = gameRoomRepository;
    }

    public async Task<GetRoomResult> Handle(GetRoomQuery request, CancellationToken cancellationToken)
    {
        try
        {
            var room = await _gameRoomRepository.GetByIdAsync(request.RoomId);
            if (room == null)
            {
                return new GetRoomResult
                {
                    Success = false,
                    ErrorMessage = "Room not found"
                };
            }

            var players = room.Players.Select(p => new PlayerInfo
            {
                Id = p.Id,
                NickName = p.NickName,
                Color = p.Color,
                Score = p.CurrentScore,
                IsOnline = p.IsOnline
            }).ToList();

            return new GetRoomResult
            {
                RoomId = room.Id,
                Name = room.Name,
                Status = room.Status.ToString(),
                MaxPlayers = room.MaxPlayers,
                CurrentPlayers = room.Players.Count,
                GameDuration = room.GameDuration,
                RemainingTime = room.GetRemainingTime(),
                CreatedBy = room.CreatedBy, // 添加房间创建者信息
                Players = players,
                Success = true
            };
        }
        catch (Exception ex)
        {
            return new GetRoomResult
            {
                Success = false,
                ErrorMessage = ex.Message
            };
        }
    }
}
